var express = require('express');
let db = require("../tools/DB");
var router = express.Router();
let md5 = require("md5");

/* GET home page. */
router.get('/', function(req, res, next) {
  let secret = "offcn.com"
  res.send( md5("11212") )
});

router.get("/login",(req,res)=>{
  res.render("login.ejs");
})
router.get("/register",(req,res)=>{
  res.render("register.ejs");
})
router.get("/userlist",async (req,res)=>{
  // 读取数据库中users表中的数据
  let sql  = "select * from users";
  let data = await db.query(sql,[]);
  res.render("userlist.ejs",{data})
  // res.json({code:200,data:data,msg:"数据获取成功"})
})

// 响应注册
router.post("/doregister",async (req,res)=>{
  let {username,password} = req.body;
  let sql = "select * from users where username=?";
  let a = await db.query(sql,[username]);
  // 如果查询结果数组的长度大于0，则说明数据库中存在和用户提交账号重复的记录
  if(a.length>0){
    // res.send("账号重复")
    res.json({code:208,data:null,msg:"账号重复"});
  }else{
    // 继续注册流程
    let sql = "insert into users(username,password) values(?,?)";
    // 将用户的明文密码加密后存储
    let pwd = md5(password);
    let b = await db.query(sql,[username,pwd]);
    if( b.affectedRows >0){
      // res.send("注册成功");
      res.json({code:200,data:[],msg:"注册成功"})
    }else{
      // res.send("注册失败，请检查")
      res.json({code:208,data:[],msg:"注册失败，请检查"})
    }
  }
})
// 响应登录
router.post("/dologin",async (req,res)=>{
  let {username,password} = req.body;
  // 将用户提交的明文密码，再次加密
  let pwd = md5(password);
  // 查询数据库中有没有和用户提交的账号密码相同的记录
  let sql = "select * from users where username=? and password = ?";
  let a = await db.query(sql,[username,pwd]);
  if(a.length>0){
    // res.send("登录成功");
    res.json({code:200,data:[],msg:"登录成功"})
  }else{
    // res.send("账号或密码错误");
    res.json({code:208,data:[],msg:"账号或密码错误"})
  }
})

// 响应删除用户
router.get("/deluser",async (req,res)=>{
  let {id} = req.query;
  let sql = "delete from users where id=?";
  let a = await db.query(sql,[id]);
  if( a.affectedRows>0){
    res.json({code:200,data:null,msg:"删除成功"});
  }else{
    res.json({code:208,data:null,msg:"删除失败，请检查参数"});
  }
})


module.exports = router;
